//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.IO;



/**
 * A collection of static file management methods.<p>
 * Also : the default FileAccess method
 *
 * @author fredt@users
 * @author boucherb@users
 * @author Ocke Janssen oj@openoffice.org
 * @version 1.8.0
 * @since 1.7.2
 */
namespace EffiProz.Core.Lib
{
    public class FileUtil : EfzFileAccess
    {

#if SILVERLIGHT
        private static FileUtilSlis fileUtil = new FileUtilSlis();
        public static EfzFileAccess GetDefaultInstance()
        {
            return fileUtil;
        }
#else
        private static FileUtil fileUtil = new FileUtil();
        public static FileUtil GetDefaultInstance()
        {
            return fileUtil;
        }
#endif

        /** Creates a new instance of FileUtil */
        public FileUtil() { }

       


        override public bool IsStreamElement(string elementName)
        {
            return File.Exists(elementName);
        }

        override public Stream OpenInputStreamElement(string streamName)
        {
            try
            {
                return new FileStream(streamName, FileMode.Open,  FileAccess.Read );
            }
            catch (Exception e)
            {
                throw toIOException(e);
            }
        }

        override public void CreateParentDirs(String filename)
        {
            FileInfo fileInfo = new FileInfo(filename);

            makeParentDirectories(fileInfo);
        }

      

        override public void RenameElement(System.String oldName,
                                  System.String newName)
        {
            renameOverwrite(oldName, newName);
        }

        override public Stream OpenOutputStreamElement(
                String streamName)
        {
            return new FileStream(streamName, FileMode.OpenOrCreate,  FileAccess.ReadWrite );
        }

        override public FileStream OpenOutputStreamElement(string streamName, FileMode mode,
            FileAccess access)
        {
            return new FileStream(streamName, mode,  access );
        }

        public override void removeElement(String filename)
        {

            if (IsStreamElement(filename))
            {
                delete(filename);
            }
        }

        // end of FileAccess implementation
        // a new File("...")'s path is not canonicalized, only resolved
        // and normalized (e.g. redundant separator chars removed),
        // so as of JDK 1.4.2, this is a valid test for case insensitivity,
        // at least when it is assumed that we are dealing with a configuration
        // that only needs to consider the host platform's native file system,
        // even if, unlike for File.getCanonicalPath(), (new File("a")).exists() or
        // (new File("A")).exits(), regardless of the hosting system's
        // file path case sensitivity policy.
        public  bool fsIsIgnoreCase ;    //    (File.OpenRead("A")).Equals(File.OpenRead("A"));

        // posix separator normalized to File.separator?
        // CHECKME: is this true for every file system under Java?
        public  bool fsNormalizesPosixSeparator =
            "/".Equals(Path.DirectorySeparatorChar);

        // for JDK 1.1 createTempFile
        Random random = new Random((int)DateTime.Now.Ticks);

        /**
         * Delete the named file
         */
        private void delete(string filename)
        {
            File.Delete(filename);
        }

        /**
         * Requests, _in a JDK 1.1 compliant way, that the file or directory denoted
         * by the given abstract pathname be deleted when the virtual machine
         * terminates. <p>
         *
         * Deletion will be attempted only for JDK 1.2 and greater runtime
         * environments and only upon normal termination of the virtual
         * machine, as defined by the Java Language Specification. <p>
         *
         * Once deletion has been sucessfully requested, it is not possible to
         * cancel the request. This method should therefore be used with care. <p>
         *
         * @param f the abstract pathname of the file be deleted when the virtual
         *       machine terminates
         */
        public override void deleteOnExit(string file)
        {
            //JavaSystem.deleteOnExit(f); TODO
        }

        /**
         * Return true or false based on whether the named file exists.
         */
        public override bool exists(string filename)
        {
            return File.Exists(filename);
        }

        public override string getParentDir(string filename)
        {
            FileInfo file = new FileInfo(filename);
            return file.Directory.FullName;
        }

        public override string[] getAllFiles(string dirName)
        {
            DirectoryInfo dir = new DirectoryInfo(dirName);
            FileInfo[] files =  dir.GetFiles();
            string[] fileNames = new string[files.Length];

            for (int i = 0; i < files.Length; i++)
                fileNames[i] = files[i].FullName;

            return fileNames;
        }

        public bool exists(string fileName, bool resource)
        {

            if (fileName == null || fileName.Length == 0)
            {
                return false;
            }

            //System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
            //bool found = false;
            //foreach (var rn _in asm.GetManifestResourceNames())
            //{
            //    if (rn == fileName)
            //        found = true;
            //}

            return exists(fileName);
        }

        /**
         * Rename the file with oldname to newname. If a file with newname already
         * exists, it is deleted before the renaming operation proceeds.
         *
         * If a file with oldname does not exist, no file will exist after the
         * operation.
         */
        private void renameOverwrite(string oldname, string newname)
        {

            delete(newname);

            if (exists(oldname))
            {
                File.Move(oldname, newname);

            }
        }

        public static IOException toIOException(Exception e)
        {

            if (e is IOException)
            {
                return (IOException)e;
            }
            else
            {
                return new IOException(e.ToString());
            }
        }

        /**
         * Retrieves the absolute path, given some path specification.
         *
         * @param path the path for which to retrieve the absolute path
         * @return the absolute path
         */
        public string absolutePath(string path)
        {
            return Path.GetFullPath(path);
        }

        ///**
        // * Retrieves the canonical file for the given file, _in a
        // * JDK 1.1 complaint way.
        // *
        // * @param f the File for which to retrieve the absolute File
        // * @return the canonical File
        // */
        //public String canonicalFile(string path)
        //{
        //    return Path.GetFullPath(path);
        //}

        /**
         * Retrieves the canonical file for the given path, _in a
         * JDK 1.1 complaint way.
         *
         * @param path the path for which to retrieve the canonical File
         * @return the canonical File
         */
        public string canonicalFile(string path)
        {
            return Path.GetFullPath(path);
        }

        ///**
        // * Retrieves the canonical path for the given File, _in a
        // * JDK 1.1 complaint way.
        // *
        // * @param f the File for which to retrieve the canonical path
        // * @return the canonical path
        // */
        //public string canonicalPath(string f)
        //{
        //    return Path.GetFullPath(f);
        //}

        /**
         * Retrieves the canonical path for the given path, _in a
         * JDK 1.1 complaint way.
         *
         * @param path the path for which to retrieve the canonical path
         * @return the canonical path
         */
        public override string canonicalPath(string path)
        {
            return Path.GetFullPath(path);
        }

        /**
         * Retrieves the canonical path for the given path, or the absolute
         * path if attemting to retrieve the canonical path fails.
         *
         * @param path the path for which to retrieve the canonical or
         *      absolute path
         * @return the canonical or absolute path
         */
        public override string CanonicalOrAbsolutePath(string path)
        {

            try
            {
                return Path.GetFullPath(path);
            }
            catch (Exception )
            {
                return absolutePath(path);
            }
        }

        public void makeParentDirectories(FileInfo f)
        {
            DirectoryInfo parent = f.Directory;

            if (!parent.Exists)
                parent.Create();

        }

        public override String makeDirectories(String path)
        {

            try
            {
                DirectoryInfo file = new DirectoryInfo(path);

                file.Create();

                return file.FullName;
            }
            catch (IOException )
            {
                return null;
            }
        }

        public class FileSync : IFileSync
        {

            FileStream outDescriptor;

            public FileSync(FileStream os)
            {
                outDescriptor = os;
            }

            public void Sync()
            {
                outDescriptor.Flush();
            }
        }

        override public IFileSync GetFileSync(Stream os)
        {
            return new FileSync((FileStream)os);
        }
    }
}
